'use client'

import React, { useState, useEffect } from 'react'
import { useRouter } from 'next/navigation'

const navigationItems = [
    { name: '首页', path: '/', submenu: [] },
    {
        name: '走进仙山八骏',
        path: '/organic-tea',
        submenu: []
    },
    { name: '有机茶园', path: '/tea-garden', submenu: [] },
    { name: '有机好茶', path: '/good-tea', submenu: [] },
    { name: '有机文化', path: '/organic-culture', submenu: [] },
    { name: '招商加盟', path: '/merchants', submenu: [] },
    { name: '品牌动态', path: '/brand', submenu: [] },
]

// 根据路径获取对应的导航项名称
const getActiveItemByPath = (pathname: string) => {
    const item = navigationItems.find(item => item.path === pathname)
    return item ? item.name : '首页'
}

export interface NavigationHeaderProps {
    textColor?: string // 传递字体颜色的 className
    logoSrc?: string // 可选的 logo 图片路径
}

export default function NavigationHeader({ textColor = 'text-white', logoSrc }: NavigationHeaderProps) {
    const router = useRouter()
    const [activeItem, setActiveItem] = useState('首页')
    const [hoveredItem, setHoveredItem] = useState('')
    const [hoverTimeout, setHoverTimeout] = useState<NodeJS.Timeout | null>(null)
    const [isScrolled, setIsScrolled] = useState(false)
    const [currentPath, setCurrentPath] = useState('')



    // 监听路径变化，更新激活状态
    useEffect(() => {
        const path = window.location.pathname
        setCurrentPath(path)
        const currentActiveItem = getActiveItemByPath(path)
        setActiveItem(currentActiveItem)
    }, [])

    // 监听滚动事件
    useEffect(() => {
        const handleScroll = () => {
            const scrollTop = window.pageYOffset || document.documentElement.scrollTop
            setIsScrolled(scrollTop > 50)
        }

        window.addEventListener('scroll', handleScroll)
        return () => window.removeEventListener('scroll', handleScroll)
    }, [])

    const handleMouseEnter = (itemName: string) => {
        if (hoverTimeout) {
            clearTimeout(hoverTimeout)
            setHoverTimeout(null)
        }
        setHoveredItem(itemName)
    }

    const handleMouseLeave = () => {
        const timeout = setTimeout(() => {
            setHoveredItem('')
        }, 100)
        setHoverTimeout(timeout)
    }

    return (
        <>
            {/* 原始导航栏 */}
            <nav className="w-full py-4 z-50 absolute">
                <div className='flex justify-center'>
                    <img src={logoSrc} className='h-[50px] w-[230px]' />
                </div>
                <div className="flex justify-center items-center mt-[30px]">
                    <ul className="flex justify-between w-full max-w-[1246px] px-4">
                        {navigationItems.map((item) => (
                            <li
                                key={item.name}
                                className="relative"
                                onMouseEnter={() => handleMouseEnter(item.name)}
                                onMouseLeave={handleMouseLeave}
                            >
                                {item.path ? (
                                    <a
                                        href={item.path}
                                        onClick={(e) => {
                                            e.preventDefault()
                                            setActiveItem(item.name)
                                            setCurrentPath(item.path)
                                            // 使用Next.js路由跳转
                                            router.push(item.path)
                                        }}
                                        className={`${item.name === '首页' ? '' : 'nav-underline'} text-[1rem] font-bold transition-colors duration-200 relative ${activeItem === item.name && item.name !== '首页'
                                            ? 'text-[#f7b401]'
                                            : `${textColor}`
                                            } hover:text-[#f7b401] active:text-[#f7b401]`}
                                    >
                                        {item.name}
                                    </a>
                                ) : (
                                    <button
                                        onClick={() => {
                                            setActiveItem(item.name)
                                        }}
                                        className={`${item.name === '首页' ? '' : 'nav-underline'} text-[1rem] font-bold transition-colors duration-200 relative ${activeItem === item.name && item.name !== '首页'
                                            ? 'text-[#f7b401]'
                                            : `${textColor}`
                                            } hover:text-[#f7b401] active:text-[#f7b401]`}
                                    >
                                        {item.name}
                                    </button>
                                )}
                                {/* 二级菜单 */}
                                {item.submenu.length > 0 && hoveredItem === item.name && (
                                    <div
                                        className="absolute top-full left-1/2 transform -translate-x-1/2 py-4 px-6 z-50"
                                        onMouseEnter={() => handleMouseEnter(item.name)}
                                        onMouseLeave={handleMouseLeave}
                                    >
                                        <div className="flex space-x-6">
                                            {item.submenu.map((subItem) => (
                                                <button
                                                    key={subItem}
                                                    className={`text-[1rem] px-3 py-2 relative font-bold hover:text-red-500 transition-colors duration-200 whitespace-nowrap ${textColor}`}
                                                    onClick={() => {
                                                        console.log('Clicked:', subItem)
                                                        setHoveredItem('')
                                                    }}
                                                >
                                                    {subItem}
                                                </button>
                                            ))}
                                        </div>
                                    </div>
                                )}
                            </li>
                        ))}
                    </ul>
                </div>
            </nav>            {/* 悬浮导航栏 */}
            <nav className={`fixed top-0 left-0 w-full bg-[#f1ebdb] backdrop-blur-md shadow-lg z-50 py-3 transition-transform duration-300 ${isScrolled ? 'translate-y-0' : '-translate-y-full'
                }`}>
                {/* Logo居中 */}
                <div className='flex justify-center'>
                    <img src="https://pub-d9c5812daa2b44e5b6d7b6621bbeb301.r2.dev/logo/logo.png" className='h-[40px] w-[184px]' alt="Logo" />
                </div>

                {/* 导航菜单居中 */}
                <div className="flex justify-center items-center mt-[20px]">
                    <ul className="flex justify-between w-full max-w-[1246px] px-4">
                        {navigationItems.map((item) => (
                            <li
                                key={`floating-${item.name}`}
                                className="relative"
                                onMouseEnter={() => handleMouseEnter(item.name)}
                                onMouseLeave={handleMouseLeave}
                            >
                                {item.path ? (
                                    <a
                                        href={item.path}
                                        onClick={(e) => {
                                            e.preventDefault()
                                            setActiveItem(item.name)
                                            setCurrentPath(item.path)
                                            // 使用Next.js路由跳转
                                            router.push(item.path)
                                        }}
                                        className={`${item.name === '首页' ? '' : 'nav-underline'} text-[0.9rem] font-bold transition-colors duration-200 relative ${activeItem === item.name && item.name !== '首页'
                                            ? 'text-[#f7b401]'
                                            : `text-[#49343d]`
                                            } hover:text-[#f7b401] active:text-[#f7b401]`}
                                    >
                                        {item.name}
                                    </a>
                                ) : (
                                    <button
                                        onClick={() => setActiveItem(item.name)}
                                        className={`${item.name === '首页' ? '' : 'nav-underline'} text-[0.9rem] font-bold transition-colors duration-200 relative ${activeItem === item.name && item.name !== '首页'
                                            ? 'text-[#f7b401]'
                                            : `text-[#49343d]`
                                            } hover:text-[#f7b401] active:text-[#f7b401]`}
                                    >
                                        {item.name}
                                    </button>
                                )}
                                {/* 二级菜单 */}
                                {item.submenu.length > 0 && hoveredItem === item.name && (
                                    <div
                                        className="absolute top-full left-1/2 transform -translate-x-1/2 py-4 px-6 z-50 bg-white/95 backdrop-blur-md rounded-lg shadow-lg mt-2"
                                        onMouseEnter={() => handleMouseEnter(item.name)}
                                        onMouseLeave={handleMouseLeave}
                                    >
                                        <div className="flex space-x-6">
                                            {item.submenu.map((subItem) => (
                                                <button
                                                    key={subItem}
                                                    className="text-[0.9rem] px-3 py-2 text-gray-800 relative font-bold hover:text-[#f7b401] transition-colors duration-200 whitespace-nowrap"
                                                    onClick={() => {
                                                        console.log('Clicked:', subItem)
                                                        setHoveredItem('')
                                                    }}
                                                >
                                                    {subItem}
                                                </button>
                                            ))}
                                        </div>
                                    </div>
                                )}
                            </li>
                        ))}
                    </ul>
                </div>
            </nav>
            <style jsx global>{`
.nav-underline::after {
    content: '';
    position: absolute;
    left: -50%;
    bottom: -4px;
    width: 200%;
    height: 3px;
    background: #f7b401;
    border-radius: 9999px;
    transform: scaleX(0);
    transition: transform 0.3s;
    z-index: 1;
    will-change: transform;
    backface-visibility: hidden;
}
.nav-underline:hover::after,
.nav-underline:focus::after {
    transform: scaleX(1);
}
.nav-underline:active {
    color: #f7b401 !important;
}

`}</style>
        </>
    )
}
